#include "TcpServer.hpp"
#include "EventLoop.hpp"
#include "TcpConnection.hpp"

#include <functional>
#include <sstream>
#include <iostream>

TcpServer::TcpServer(EventLoop* loop, const sockaddr_in& listenAddr, int numThreads)
    : loop_(loop),
      acceptor_(new Acceptor(loop, listenAddr)),
      threadNum_(numThreads),
      threadPool_(new EventLoopThreadPool(loop, numThreads)) {
    
    acceptor_->setNewConnectionCallback(
        std::bind(&TcpServer::newConnection, this, std::placeholders::_1, std::placeholders::_2)
    );
}

TcpServer::~TcpServer() = default;

void TcpServer::start() {
    threadPool_->start();
    acceptor_->listen();
}

void TcpServer::newConnection(int sockfd, const sockaddr_in& peerAddr) {
    EventLoop* ioLoop = threadPool_->getNextLoop();
    // 构建连接名
    std::ostringstream oss;
    oss << "conn#" << nextConnId_++;
    std::string connName = oss.str();

    std::cout << "New connection: " << connName
              << ", fd = " << sockfd
              << ", assigned to thread " << ioLoop << std::endl;

    // 创建 TcpConnection
    auto conn = std::make_shared<TcpConnection>(ioLoop, sockfd, peerAddr);
    connections_[connName] = conn;

    // 设置回调
    conn->setConnectionCallback(connectionCallback_);
    conn->setMessageCallback(messageCallback_);
    conn->setCloseCallback(std::bind(&TcpServer::removeConnection, this, std::placeholders::_1));
    // 建立连接（注册事件）
    ioLoop->queueInLoop([conn] {
        conn->connectEstablished();
    });
    // {
    //     std::lock_guard<std::mutex> lk(m);
    //     conn->connectEstablished();
    // }
}

void TcpServer::removeConnection(const TcpConnection::TcpConnectionPtr& conn) {
    loop_->queueInLoop([this, conn] {
        for (auto it = connections_.begin(); it != connections_.end(); ++it) {
            if (it->second == conn) {
                std::cout << "Remove connection: " << it->first << std::endl;
                connections_.erase(it);
                break;
            }
        }
    });
}
